package ysq.xyg.interceptor;

import com.github.pagehelper.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import ysq.xyg.model.info.BaseUserInfo;
import ysq.xyg.util.BaseConstant;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yu sheng qiang
 * @create 2017-03-03 8:32
 **/
public class LoginInterceptor extends HandlerInterceptorAdapter{
    private static Log log= LogFactory.getLog(LoginInterceptor.class);
    public static List<String> pattenURL = new ArrayList<String>();
    public static List<String> pattenDIR = new ArrayList<String>();
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        initURL();
        String url = request.getRequestURI().toString();
        if(StringUtil.isNotEmpty(url) && url.indexOf(".txt")>-1){
            return true;
        }
        log.info("-------------url-" + url + "--------------");
        for (String urlStr : pattenURL) {
            if (url.equals(urlStr)) {
                log.info("-------------" + urlStr + "-" + url + "--------------");
                return true;
            }
        }
        for (String urlStr : pattenDIR) {
            if (StringUtil.isNotEmpty(url) && StringUtil.isNotEmpty(url) && urlStr.length() < url.length() && url.substring(0,urlStr.length()).equals(urlStr)) {
                log.info("-------------" + urlStr + "-" + url + "---"+url.substring(0,urlStr.length())+"-----------");
                return true;
            }
        }
        BaseUserInfo baseUserInfo=(BaseUserInfo) request.getSession().getAttribute(BaseConstant.SESSION_USERINFO);
        if(baseUserInfo!=null || "".equals(baseUserInfo)){
            log.info("-------------userInfo-"+baseUserInfo.toString()+"--------------");
            return true;
        }else{
            response.sendRedirect("/");
            return false;
        }
    }
    public void initURL(){
        pattenURL.add("/");
        pattenURL.add("/user/login");
    }
    public void initDIR(){
        pattenURL.add("/phone/");
    }

}
